package com.example.stlink.utils;

import android.os.Handler;
import android.os.Message;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.example.stlink.R;


// 继承抽象类BDAbstractListener并重写其onReceieveLocation方法来获取定位数据，并将其传给MapView
public class MyLocationListener extends BDAbstractLocationListener {

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private Handler handler;

    private BDLocation retLocation;

    // 是否是第一次定位
    public static boolean isFirstLocate = true;
    // 当前定位模式
    private MyLocationConfiguration.LocationMode locationMode;

    public MyLocationListener(MapView mMapView, BaiduMap mBaiduMap, Handler handler){
        this.mMapView = mMapView;
        this.mBaiduMap = mBaiduMap;
        this.handler = handler;
    }

    @Override
    public void onReceiveLocation(BDLocation location) {

        retLocation = location;

        //mapView 销毁后不在处理新接收的位置
        if (location == null || mMapView == null){
            return;
        }
        LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
//         //如果是第一次定位
//        if (isFirstLocate) {
//            isFirstLocate = false;
            //给地图设置状态
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(ll));
//        }

        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(location.getRadius())
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(location.getDirection()).latitude(location.getLatitude())
                .longitude(location.getLongitude()).build();
        mBaiduMap.setMyLocationData(locData);

        // ------------------  以下是可选部分 ------------------
        // 自定义地图样式，可选
        // 更换定位图标，这里的图片是放在 mipmap 文件下的
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.mipmap.location);
        // 定位模式 地图SDK支持三种定位模式：NORMAL（普通态）, FOLLOWING（跟随态）, COMPASS（罗盘态）
        locationMode = MyLocationConfiguration.LocationMode.NORMAL;
        // 定位模式、是否开启方向、设置自定义定位图标、精度圈填充颜色以及精度圈边框颜色5个属性（此处只设置了前三个）。
        MyLocationConfiguration mLocationConfiguration = new MyLocationConfiguration(locationMode,true,mCurrentMarker);
        // 使自定义的配置生效
        mBaiduMap.setMyLocationConfiguration(mLocationConfiguration);
        // ------------------  可选部分结束 ------------------

        Message msg = new Message();
        msg.arg1 = 200;
        handler.sendMessage(msg);
    }

    public BDLocation getLocation(){
        return retLocation;
    }

}